<template>
  <div class="upload-list">
    <div class="operate-btns">
      <el-select
        v-model="search.status"
        :placeholder="$t('websocket.messageStatus')"
      >
        <el-option
          v-for="item in stateOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="searchList">{{
        $t('common.search')
      }}</el-button>
      <el-button
        type="primary"
        :disabled="isDisabled"
        class="delete"
        icon="el-icon-document-checked"
        @click="signMessageReads"
      >
        {{ $t('websocket.read') }}
        <span v-show="deleteNums">({{ deleteNums }})</span>
      </el-button>
      <el-button
        type="danger"
        :disabled="isDisabled"
        class="delete"
        icon="el-icon-delete"
        @click="deleteMessages"
      >
        {{ $t('common.delete') }}
        <span v-show="deleteNums">({{ deleteNums }})</span>
      </el-button>
    </div>
    <el-table
      ref="multipleTable"
      :data="messageList"
      style="width: 100%"
      stripe
      border
      :row-key="getRowKeys"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
    >
      <el-table-column
        type="selection"
        width="55"
        :reserve-selection="true"
        align="center"
      />
      <el-table-column
        type="index"
        :label="$t('common.num')"
        width="50"
        align="center"
      />
      <el-table-column prop="type" :label="$t('websocket.messageContent')">
        <template slot-scope="scope">
          <span
            :class="{
              success: scope.row.type.indexOf('success') > 0,
              danger: scope.row.type.indexOf('fail') > 0
            }"
          >
            {{ showContent(scope.row.type) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        :label="$t('websocket.receiveTime')"
        width="200"
      >
        <template slot-scope="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        :label="$t('websocket.messageStatus')"
        align="center"
        width="120"
      >
        <template slot-scope="scope">
          <span
            :class="{
              success: scope.row.status === 'read',
              danger: scope.row.status === 'unread'
            }"
          >{{ showStatus(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.operate')" align="center" width="220">
        <template slot-scope="scope">
          <el-button
            type="primary"
            plain
            @click="signMessageRead(scope.row)"
          >{{ $t('websocket.read') }}
          </el-button>
          <el-button type="danger" plain @click="deleteMessage(scope.row)">{{
            $t('common.delete')
          }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pager">
      <el-pagination
        :current-page="search.page"
        :page-sizes="[10, 50, 100, 400]"
        :page-size="search.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totals"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { formatDate } from '@/utils/index';
import {
  getMessagesList,
  deleteMessage,
  signMessageRead,
} from '@/api/websocket';
import { mapGetters } from 'vuex';

export default {
  name: 'MyNotice',
  data() {
    return {
      totals: 0,
      messageList: [],
      search: {
        status: '',
        page: 1,
        size: 10,
      },
      isDisabled: true,
      multipleSelection: [],
      deleteNums: null,
      selectNoticesIds: [],
    };
  },
  computed: {
    ...mapGetters(['name']),
    stateOptions() {
      return [
        {
          label: this.$t('websocket.allMessages'),
          value: '',
        },
        {
          label: this.$t('websocket.read'),
          value: 'read',
        },
        {
          label: this.$t('websocket.unread'),
          value: 'unread',
        },
      ];
    },
  },
  created() {
    this.init();
  },
  methods: {
    /**
     * 页面初始化方法
     */
    init() {
      this.getList();
    },
    /**
     * 获取消息列表
     */
    async getList() {
      const res = await getMessagesList(this.search);
      this.messageList = res.data;
      this.totals = Number(res.headers['x-total-count']);
    },
    /**
     * 按消息状态搜索
     */
    searchList() {
      this.getList();
    },
    /**
     * 根据表格的排序条件发生变化触发请求
     * @param {Object} row 表格栏目对象（包含每条栏目的数据和属性）
     */
    handleSortChange(row) {
      this.search.page = 1;
      this.getList();
    },
    /**
     * 删除单条消息接口处理
     * @param {Object} row 删除消息详细数据
     */
    deleteMessage(row) {
      this.$confirm(this.$t('websocket.tip01'), this.$t('common.tips'), {
        confirmButtonText: this.$t('common.sure'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning',
      }).then(() => {
        deleteMessage([row.id]).then(() => {
          this.$message.success(this.$t('websocket.deleteSuccess'));
          this.getList();
        });
      });
    },
    /**
     * 批量删除消息
     */
    deleteMessages() {
      this.$confirm(this.$t('websocket.tip02'), this.$t('common.tips'), {
        confirmButtonText: this.$t('common.sure'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning',
      }).then(() => {
        this.multipleDelete();
      });
    },
    /**
     * 批量删除接口
     */
    multipleDelete() {
      const ids = this.selectNoticesIds;
      deleteMessage(ids).then(() => {
        this.$message.success(this.$t('websocket.deleteSuccess'));
        this.getList();
        this.clearMultipleSelect();
      });
    },
    /**
     * 单条消息标记已读处理逻辑
     * @param {Object} row 单条消息详细数据
     */
    signMessageRead(row) {
      signMessageRead([row.id]).then(res => {
        this.$message.success(this.$t('websocket.tip03'));
        this.getList();
      });
    },
    /**
     * 批量标记消息已读
     */
    signMessageReads() {
      this.$confirm(this.$t('websocket.tip04'), this.$t('common.tips'), {
        confirmButtonText: this.$t('common.sure'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning',
      }).then(() => {
        this.multipleRead();
      });
    },
    /**
     * 批量标记消息已读接口
     */
    multipleRead() {
      const ids = this.selectNoticesIds;
      signMessageRead(ids).then(res => {
        this.$message.success(this.$t('websocket.tip03'));
        this.getList();
        this.clearMultipleSelect();
      });
    },
    /**
     * 分页组件-改变每页条数
     */
    handleSizeChange(val) {
      this.search.size = val;
      this.getList();
    },
    /**
     * 分页组件-改变页码
     */
    handleCurrentChange(val) {
      this.search.page = val;
      this.getList();
    },
    /**
     * 分页多选 element ui 组件自带功能
     */
    getRowKeys(row) {
      return row.id;
    },
    /**
     * 消息列表多选操作
     * @param {Arrary} val 已选择条目数据
     */
    handleSelectionChange(val) {
      if (val.length) {
        this.selectNoticesIds = [];
        this.multipleSelection = [];
        this.multipleSelection.push(...val);
        this.multipleSelection.filter(item => {
          return this.selectNoticesIds.push(item.id);
        });
        if (this.multipleSelection.length) {
          this.isDisabled = false;
          this.deleteNums = this.multipleSelection.length;
        } else {
          this.isDisabled = true;
          this.deleteNums = null;
        }
      } else {
        this.isDisabled = true;
        this.deleteNums = null;
        this.selectNoticesIds = [];
        this.multipleSelection = [];
      }
    },
    /**
     * 清空多选操作
     */
    clearMultipleSelect() {
      this.deleteNums = null;
      this.isDisabled = true;
      this.selectNoticesIds = [];
      this.$refs.multipleTable.clearSelection();
    },
    /**
     * 日期格式化处理
     * @param {Date} date 待处理日期
     */
    formatDate(date) {
      return formatDate(new Date(date));
    },
    /**
     * 展示消息状态
     * @param {String} status read or unread
     */
    showStatus(status) {
      let showText;
      const existsText = ['read', 'unread'];
      if (existsText.includes(status)) {
        showText = this.$t(`websocket.${status}`);
      } else {
        showText = this.$t('common.unknown');
      }
      return showText;
    },
    /**
     * 展示消息状态
     * @param {String} type
     * sync_all_user_success：同步用户成功；
     * sync_all_user_fail：同步用户失败；
     * sync_all_organization_success：同步部门成功；
     * sync_all_organization_fail：同步部门失败；
     * sync_increment_organization_success：增量同步部门成功；
     * sync_increment_user_success：增量同步用户成功；
     */
    showContent(type) {
      let showText;
      const existsText = [
        'sync_all_user_success',
        'sync_all_user_fail',
        'sync_all_organization_success',
        'sync_all_organization_fail',
        'sync_increment_organization_success',
        'sync_increment_user_success',
      ];
      if (existsText.includes(type)) {
        showText = this.$t(`websocket.${type}`);
      } else {
        showText = this.$t('common.unknown');
      }
      return showText;
    },
  },
};
</script>
<style scoped>
/* 表格样式问题重置 */
.upload-list /deep/ .el-table--border th.gutter:last-of-type {
  display: block !important;
  width: 17px !important;
}
</style>
<style lang="scss" scoped>
.upload-list {
  padding: 20px;
  .tab-content-box {
    padding-left: 10px;
  }
  .operate-btns {
    margin: 20px 0;
    overflow: hidden;
  }
  .pager {
    margin: 20px 0;
    text-align: right;
  }
}
.brand {
  color: #409eff;
}
.danger {
  color: #f56c6c;
}
.success {
  color: #67c23a;
}
</style>
